package com.example.demo.handler;

import com.alibaba.fastjson.JSON;

import com.example.demo.uilt.JwtUtil;
import com.example.demo.uilt.RedisCache;
import com.example.demo.uilt.ResponseResult;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    RedisCache redisCache;
    @SneakyThrows
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.OK.value(), "退出成功!");
        String json = JSON.toJSONString(result);
        String token = request.getHeader("token");
        String subject = JwtUtil.parseJWT(token).getSubject();
        //Authentication 中存储的是用户的信息，通过判断用户信息是否为空来判断他能不能退出
        if (StringUtils.hasText(token)){
            redisCache.deleteObject("login:"+subject);
        }
        SecurityContextHolder.getContext().getAuthentication();
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(json);
    }
}
